<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\Admin\PointsMall;
use App\Models\Admin\PointsMallOrder;
use App\Models\IntegralLog;
use App\Models\ShopAccount;
use App\Models\User;
use App\Service\HttpService;
use App\Service\PointsMallService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Banner;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class MallController extends Controller
{
    CONST PER_PAGE = 10;

    /**
     *  获取积分商品的列表
     * @param PointsMall $pointsMall
     * @param PointsMallOrder $pointsMallOrder
     * @param HttpService $httpService
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function mallList(PointsMall $pointsMall,PointsMallOrder $pointsMallOrder,HttpService $httpService){

        $banner = Banner::where('type',1)->get();

        $hotList = $pointsMall->where('is_hot',2)->where('status',1)->limit(2)->get();

        $newList = $pointsMall->where('is_new',2)->where('status',1)->limit(2)->get();

        return tips(1,'success',[
            'banner' => $banner,
            'hotList' => $hotList,
            'newList' => $newList,
            'img_url' => img_url()
        ]);



    }

    /**
     *
     * 获取 所有的商品
     * @author Bryant
     * @date 2020-10-17 14:28
     *
     *
     */
    public function getAllList(PointsMall $pointsMall,HttpService $httpService)
    {
        $start_point = request('start_point','');
        $end_point = request('end_point','');
        $where = [];
        if($start_point){
            $where []= ['point','>=',$start_point];

        }
        if($end_point){
            $where []= ['point','<=',$end_point];
        }

        $pointsList = $pointsMall->where('status',1)->where($where)->paginate(4);
        return tips(1,'success',[
            'pointList'=>$pointsList,
            'img_url' => config('app.img_url')
        ]);

    }

    /**
     * 获取积分商品详情
     * @param PointsMall $pointsMall
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMallRow(PointsMall $pointsMall){

        $mall_id = request('mall_id')??'';
        if(!$mall_id){
            return tips(-1,'error','参数错误');
        }

        $mall = $pointsMall->getMallInfo(['id'=>$mall_id]);
        $mall->path = img_url();
        return tips(1,'success',$mall??[]);
    }

    /**
     * 积分换好礼
     * @param PointsMall $pointsMall
     * @param HttpService $httpService
     * @return array|\Illuminate\Contracts\Foundation\Application|\Illuminate\Http\JsonResponse|Request|string
     */
    public function mallOrder(PointsMall $pointsMall,HttpService $httpService,PointsMallOrder $pointsMallOrder,IntegralLog $integralLog)
    {

        $mobile = request('mobile');
        if(!checkMobile($mobile)){
            return tips(-1,'error','手机号码格式错误');
        }
        $url = config('app.url').'member_check?mobile='.$mobile;

        try {
            $res = $httpService->HttpRequest($url, 'GET');
        }catch (\Exception $e){
            return tips(-1,'error',$e->getMessage());
        } catch (GuzzleException $e) {
            return tips(-1,'error',$e->getMessage());
        }


        if($res['status'] == -1){
            return tips(-1,'error','未注册会员');
        }

        // 会员积分块没有接
        $mall_id = request('mall_id')??'';
        if(!$mall_id){


            return tips(-1,'error','参数错误');
        }
        // 查询会员积分
        $queryStr = request(['queryStr']); // 参数根据手机号
        $user = $this->memberQueryWithBalance($httpService,$queryStr);
        if(!$user){

            return tips(-1, 'error', '用户信息错误');
        }
        $point = $user['Point'];
        // 查询商品积分
        $mall = $pointsMall->getMallInfo(['id'=>$mall_id]);
        // 判断商品库存
        if ($mall['sku_num'] <= 0) {

            return tips(-1,'error','该商品库存不足');
        }
        // 判断商品状态
        if ($mall['status'] != 1) {

            return tips(-1,'error','该商品已下架');

        }
        // 判断用户积分
        if ($point < $mall['point']) {

            return tips(-1,'error','您的积分不足');
        }


        // 加入订单表 处理商品库存
        DB::beginTransaction();
        try {

            // 优惠券兑换
            if ($mall['type'] == 2) {

                // 获取CRM 的数据
                $getUrl = "http://8.129.17.60:8898"; //C# 中间件的访问地址
                $params = [
                    'action' => 'DT_COUPONISSUANCE_REQ',
                    'ZCOUPXH' => $mall['coupon_code'],
                    //'ZPARTNER_ID'=> "",
                    'ZCPNUMTO' => "1",
                    'ZCPBDDAT' => date('Y-m-d', time()),
                    'ZREFIELD2' => 'HNX',
                    'ZREFIELD3' => $mobile

                ];
                $params = json_encode($params, true);
                //dd($param);
                $res = $this->curl_open($getUrl, $params);
                if ($res['rtval']['T_RETURN'][0]['TYPE'] == 'S') {
                    $nums = rand(100000, 999999);
                    // 获取CRM 的数据
                    $getUrl = "http://8.129.17.60:8898"; //C# 中间件的访问地址

                    $param = [
                        'action' => 'ZRFC_POINTS_PAY', //访问的方法
                        'ZZCHANNEL' => "HNX", // 渠道
                        'PARTNER_ID' => $user['VCardNO'], // 会员号
                        'ZZAUART' => 'S04',
                        'ZZCPSTORE' => "SZ09997",
                        'ZZVBELN' => date('YmdHis', time()) . $nums,
                        'ZZCPSYDAT' => date('YmdHis', time()),
                        'ZZPOINT_RED' => $mall['point'],
                        'ZZPRODUCTS_ID' => 'HNXDH',
                        'ZZPOINT_REDSpecified' => true,

                    ];
                    $param = json_encode($param, true);

                    $resss = $this->curl_open($getUrl, $param);
                    // 机制特殊需要重新连一次
                    if ($resss['errcode'] == 4002) {

                        $resss = $this->curl_open($getUrl, $param);
                    }


                    if ($resss['rtval']['TYPE'] != 'S') {

                        throw new \Exception($resss['rtval']['MESSAGE']);
                    }
                    $num = request('num',1);
                    $datas['order_num'] = 'HNX'. date('YmdHis') . rand(10000,99999);
                    $datas['num'] = $num;
                    //$data['']
                    $datas['mall_id'] = $mall_id;
                    $datas['mobile'] = $mobile;
                    $datas['point'] = $mall['point'];
                    $datas['total_point'] = $mall['point'];
                    $datas['status'] = 1; // 初始化状态
                    $datas['created_at'] = date('Y-m-d H:i:s',time());
                    $datas['type'] = 2; // 优惠券的订单
                    $coupon_num = $res['rtval']['T_OUT_ISSUANCE'][0]['ZZCPIDO'] ?? 0;
                    $datas['coupon_num'] = $coupon_num; // 优惠券返回的优惠券编号
                    $pointsMallOrder->insert($datas);

                    // 商品库存的扣减
                    $pointsMall->where('id',$mall_id)->decrement('sku_num',$num);
                    // 销量增加
                    $pointsMall->where('id',$mall_id)->increment('sale_num',$num);
                    // 积分扣减记录
                    $data = [

                        'integral' => $mall['point'],
                        'from_type' => 3, // 积分商城
                        'type' => 2, //扣减
                        'mobile' => $mobile,
                        'created_at' => date('Y-m-d H:i:s', time())
                    ];
                    // 加入记录表
                    $result = $integralLog->insert($data);
                } else {
                    throw new \Exception(-1, 'error', $res['rtval']['T_RETURN'][0]['MESSAGE']);
                }

            } else {
                // 普通积分的抵扣

                $nums = rand(100000, 999999);
                // 获取CRM 的数据
                $getUrl = "http://8.129.17.60:8898"; //C# 中间件的访问地址

                $param = [
                    'action' => 'ZRFC_POINTS_PAY', //访问的方法
                    'ZZCHANNEL' => "HNX", // 渠道
                    'PARTNER_ID' => $user['VCardNO'], // 会员号
                    'ZZAUART' => 'S04',
                    'ZZCPSTORE' => "WH00001",
                    'ZZVBELN' => date('YmdHis', time()) . $nums,
                    'ZZCPSYDAT' => date('YmdHis', time()),
                    'ZZPOINT_RED' => $mall['point'],
                    'ZZPRODUCTS_ID' => 'HDJF',
                    'ZZPOINT_REDSpecified' => true,

                ];
                $param = json_encode($param, true);

                $res = $this->curl_open($getUrl, $param);
                // 机制特殊需要重新连一次
                if ($res['errcode'] == 4002) {

                    $res = $this->curl_open($getUrl, $param);
                }

                if ($res['rtval']['TYPE'] != 'S') {

                    throw new \Exception($res['rtval']['MESSAGE']);
                }

                $num = request('num',1);
                $datas['order_num'] = 'HNX'. date('YmdHis') . rand(10000,99999);
                $datas['num'] = $num;
                //$data['']
                $datas['mall_id'] = $mall_id;
                $datas['mobile'] = $mobile;
                $datas['point'] = $mall['point'];
                $datas['total_point'] = $mall['point'];
                $datas['status'] = 1; // 初始化状态
                $datas['created_at'] = date('Y-m-d H:i:s',time());
                $datas['type'] = 1; // 普通订单
                $pointsMallOrder->insert($datas);

                // 商品库存的扣减
                $pointsMall->where('id',$mall_id)->decrement('sku_num',$num);
                // 销量增加
                $pointsMall->where('id',$mall_id)->increment('sale_num',$num);

                // 积分扣减记录
                $data = [

                    'integral' => $mall['point'],
                    'from_type' => 3, // 积分商城
                    'type' => 2, //扣减
                    'mobile' => $mobile,
                    'created_at' => date('Y-m-d H:i:s', time())
                ];
                // 加入记录表
                $result = $integralLog->insert($data);
            }


        } catch (\Exception $e) {
            DB::rollBack();
            return tips(-1,'error',$e->getMessage());
        }
        DB::commit();
        return tips(1,'success','兑换成功');

    }

    /**
     *
     * @param Request $request
     * @param PointsMallOrder $pointsMallOrder
     * @author Bryant
     * @date 2020-10-13 11:04
     *
     * 查看用户的积分订单
     */
    public function getUserOrder(Request $request,PointsMallOrder $pointsMallOrder,HttpService $httpService)
    {
        $mobile = request('mobile');

        $type = request('type',1);
        // 检查手机号
        if (!checkMobile($mobile)) {

            return tips(-1,'error','手机号码格式错误');
        }

        // 判断用户是否注册周黑鸭会员
        $isUser = $this->isUser($httpService,$mobile);

        if ($isUser['status'] == -1 || $isUser['status'] == 0) {

            return tips(-1, 'error', '该用户没有注册周黑鸭会员');
        }
        if($type == 1){
            // 查询用户的积分订单
            $orderList = $pointsMallOrder->where('mobile',$mobile)->where('status',1)->with('mall')->paginate();
        }else{
            // 查询用户的积分订单
            $orderList = $pointsMallOrder->where('mobile',$mobile)->where('status',2)->with('mall')->paginate();
        }


        return tips(-1,'success',['orderList'=>$orderList,'img_url'=>img_url()]);

    }

    /**
     *
     * @author Bryant
     * @date 2020-10-13 13:57
     *
     * 生成订单的核销二维码
     */
    public function getOrderQrcode(PointsMallOrder $pointsMallOrder,HttpService $httpService,PointsMall $pointsMall)
    {
        $order_id = request('order_id');
        // 获取订单信息
        $orderInfo = $pointsMallOrder->where('id',$order_id)->first();

        if ($orderInfo['status'] != 1) {

            return tips(-1,'error','订单状态不允许操作');
        }

        if ($orderInfo['type'] == 2) {

            return tips(-1,'error','优惠券请前往卡包使用');
        }

        // 查询商品信息
        $goodsInfo = $pointsMall->where('id',$orderInfo['mall_id'])->first();


        $qr_path = "./uploads/";
        if (!file_exists($qr_path.'sp/')) {

            mkdir($qr_path.'sp/', 0700,true);//判断保存目录是否存在，不存在自动生成文件目录
        }
        $filename = 'sp/'.time().'.png';
        $file = $qr_path.$filename;
        dd($file);
        $access = $this->getAccent($httpService);


        $access_token= $access['access_token'];

        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;

        $qrcode = array(
            'scene'			=> 'id='.$order_id,//二维码所带参数
            'width'			=> 300,
            'page'			=> 'pages/shopWriteOff/sureOrder/sureOrder',//二维码跳转路径（要已发布小程序）
            'auto_color'	=> true
        );

        $result = $httpService->HttpRequest($url,'POST',$qrcode);//请求微信接口


        // 错误码
        $errcode = json_decode($result,true)['errcode'];
        // 错误信息
        $errmsg = json_decode($result,true)['errmsg'];

        if ($errcode) {

            return tips(-1,'error',$errmsg);
        }

        $res = file_put_contents($file,$result);//将微信返回的图片数据流写入文件


        //判断是否已存在该二维码图片
        $img = $pointsMallOrder->where('id',$order_id)->value('order_qrcode');


        if ($res===false) {

            return tips(-1,'error','生成二维码失败');

        } else {
                //返回图片地址链接给前端，入库操作
                $fName = '/uploads/'.$filename;

                if (isset($img) && !empty($img)){
                    //返回图片链接信息
                    return tips(1,'success',['img'=>$img,'goodsInfo'=>$goodsInfo]);
                }else{
                    //否则，添加一条新的记录
                    $dataArr['order_qrcode'] = $fName ;
                    $pointsMallOrder->where('id',$order_id)->update($dataArr);
                    return tips(1,'success',['img'=>$fName,'goodsInfo'=>$goodsInfo]);
                }
        }

    }

    /**
     *
     * @author Bryant
     * @date 2020-10-13 15:08
     *
     * 门店核销订单二维码
     */
    public function unsetQrcode(PointsMallOrder $pointsMallOrder)
    {
        $order_id = request('order_id');

        if (!$order_id) {

            return tips(-1,'error','参数错误');
        }
        $orderInfo = $pointsMallOrder->where('id',$order_id)->first();

        if ($orderInfo['status'] != 1) {

            return tips(-1,'error','订单状态不允许操作');
        }

        $res = $pointsMallOrder->where('id',$order_id)->update(['status'=>2]);

        // 成功删除二维码
        if ($res) {

            unlink('.'.$orderInfo['order_qrcode']);
        }

        return tips(1,'success','核销成功');


    }


    /**
     *
     * @param PointsMallOrder $pointsMallOrder
     * @author Bryant
     * @date 2020-10-23 11:12
     *
     * 员工核销页面
     */
    public function unView(PointsMallOrder $pointsMallOrder)
    {
        $order_id = request('order_id');

        if (!$order_id) {

            return tips(-1,'error','参数错误');
        }
        $orderInfo = $pointsMallOrder->with('mall')->where('id',$order_id)->first();

        $userInfo = User::where('mobile',$orderInfo['mobile'])->first();


        return tips(1,'success',[
            'orderInfo' => $orderInfo,
            'userInfo' => $userInfo,
            'img_url' => img_url(),
        ]);
    }


    /**
     *
     * @param ShopAccount $shopAccount
     * @author Bryant
     * @date 2020-10-23 18:31
     *
     * 门店登录
     */
    public function shopLogin(ShopAccount $shopAccount)
    {
        $account = request('account');
        $password = request('password');

        $info = $shopAccount -> where('account',$account)->first();

        if (!$info) {
            return tips(-1,'error','该账号不存在');
        }

        if (!Hash::check($password,$info['password'])) {

            return tips(-1,'error','密码错误');
        }

        return tips(1,'success','登录成功');

    }


    /**
     *
     * @author Bryant
     * @date 2020-12-01 14:23
     *
     * 获取活动内容二维码
     */
    public function getInfoImg(HttpService $httpService)
    {
        $qr_path = "./uploads/";
        if (!file_exists($qr_path.'sp/')) {

            mkdir($qr_path.'sp/', 0700,true);//判断保存目录是否存在，不存在自动生成文件目录
        }
        $filename = 'sp/'.time().'.png';
        $file = $qr_path.$filename;
        $order_id =2;
        $access = $this->getAccent($httpService);

        $access_token= $access['access_token'];

        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;

        $qrcode = array(
            'scene'			=> 'id='.$order_id,//二维码所带参数
            'width'			=> 300,
            'page'			=> 'pages/distributionCenter/makeMoney/makeMoney',//二维码跳转路径（要已发布小程序）
            'auto_color'	=> true
        );

        $result = $httpService->HttpRequest($url,'POST',$qrcode);//请求微信接口


        // 错误码
        $errcode = json_decode($result,true)['errcode'];
        // 错误信息
        $errmsg = json_decode($result,true)['errmsg'];
        if ($errcode) {

            return tips(-1,'error',$errmsg);
        }
        $res = file_put_contents($file,$result);//将微信返回的图片数据流写入文件
        if ($res===false) {

            return tips(-1,'error','生成二维码失败');

        } else {
            //返回图片地址链接给前端，入库操作
            $fName = app_paths().'/uploads/'.$filename;
                return tips(1,'success',['img'=>$fName]);
        }
    }


    /**
     *
     * @author Bryant
     * @date 2020-12-17 14:21
     *
     * 活动的小程序码
     */
    public function getActivies(HttpService $httpService)
    {
        $qr_path = "./uploads/";
        if (!file_exists($qr_path.'sp/')) {

            mkdir($qr_path.'sp/', 0700,true);//判断保存目录是否存在，不存在自动生成文件目录
        }
        $filename = 'sp/'.time().'.png';
        $file = $qr_path.$filename;
        $access = $this->getAccent($httpService);
        $access_token= $access['access_token'];

        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;

        $qrcode = array(
            'scene'			=> 'store=ZC0402',//二维码所带参数
            'width'			=> 300,
            'page'			=> 'pages/activity/activity',//二维码跳转路径（要已发布小程序）
            'auto_color'	=> true
        );

        $result = $httpService->HttpRequest($url,'POST',$qrcode);//请求微信接口


        // 错误码
        $errcode = json_decode($result,true)['errcode'];
        // 错误信息
        $errmsg = json_decode($result,true)['errmsg'];
        if ($errcode) {

            return tips(-1,'error',$errmsg);
        }
        $res = file_put_contents($file,$result);//将微信返回的图片数据流写入文件
        if ($res===false) {

            return tips(-1,'error','生成二维码失败');

        } else {
            //返回图片地址链接给前端，入库操作
            $fName = app_paths().'/uploads/'.$filename;
            return tips(1,'success',['img'=>$fName]);
        }
    }



}
